<?php   if (!defined('BASEPATH')) exit('No direct script access allowed');


class Lettere_model extends CI_Model {
	
    function __construct()
    {
        parent::__construct();
    }

    function delete($where)
	{
        $this->db->where($where);
		$this->db->delete('lettere');
        return $this->db->affected_rows() > 0;
	}
    
    function save($data)
    {
        
   		if(!isset($data['id']) || !$data['id'])
        {
            $query = $this->db->query("SELECT max(id) as id FROM lettere");
            $row = $query->row_array();
            $data['id'] = $row['id']+1;
			
            
            $this->db->insert('lettere', $data);
        }
        else
        {
            $this->db->where('id', $data['id']);
			
            $this->db->update('lettere', $data);
        }
		return $data['id'];

    }

	
    function get_columns()
	{
		$sql = "SELECT column_name from information_schema.columns where
table_name='" . $this->db->dbprefix('lettere') . "'";
		$query = $this->db->query($sql);
		
		return $query->result_array();
	}
	
    
    function get_anni()
    {
        $sql = "SELECT distinct extract(year from data) as anno FROM offerte ORDER BY extract(year from data)";
        $query = $this->db->query($sql);
        
        return $query->result_array();
    }
    
    
	function get_total($params = array())
	{
		$default_params = array
		(
			'where' => null
		);
        
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
        
		$this->db->select('count(l.id) as nb');
		$this->db->from('lettere as l');
		
		if(!is_null($params['where']))
		{
			$this->db->where( $params['where']);
		}
		$query = $this->db->get();
		
		//echo $this->db->last_query();
		$row = $query->row();
		return $row->nb;
	}
	
	function get_list($params = array())
	{
		$default_params = array
		(
			'select' => 'l.*',
			'order_by' => 'l.nome',
			'limit' => null,
			'where' => null,
			'start' => 0,
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
	
		$this->db->select($params['select']);
		$this->db->from('lettere as l');
		//$this->db->distinct();
		
		if(!is_null($params['where']))
		{
			$this->db->where($params['where']);
		}
		$this->db->order_by($params['order_by']);
		
		if(!is_null($params['limit']))
		{
			$this->db->limit($params['limit'], $params['start']);
		}
		
		$query = $this->db->get();
		return $query->result_array();
	}

	
	
}